<template>
  <!-- 电吹风-刷卡明细 -->
  <div class="swipe_details">
    <el-form :inline="true" :model="elform" size="mini">
      <el-form-item label="部门:">
        <el-select
          v-model="departmentGuid"
          placeholder="请选择"
          size="mini"
          clearable
          @change="selectdepartment"
          multiple
        >
          <el-option
            v-for="item in departmentoptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名:">
        <el-input v-model="userName" placeholder="姓名" size="mini" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="卡号:">
        <el-input v-model="cardNumber" placeholder="卡号" size="mini" clearable style="width: 120px"></el-input>
      </el-form-item>
      <el-form-item label="编号:">
        <el-input v-model="userNumber" placeholder="编号" size="mini" clearable style="width: 120px"></el-input>
      </el-form-item>

      <el-form-item label label-width="40px">
        <el-checkbox v-model="includeNoSuccess">是否包含非确定交易</el-checkbox>
      </el-form-item>
      <!-- <el-form-item label="分组:">
        <el-select
          v-model="groupingGuid"
          placeholder="请选择"
          size="mini"
          clearable
          @change="selectdepartment"
          multiple
        >
          <el-option
            v-for="item in groupingoption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="开始日期:">
        <el-date-picker
          v-model="datetime[0]"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="开始日期"
          style="width: 130px"
          size="mini"
          :clearable="false"
        ></el-date-picker>
        <el-time-picker
          style="width:110px"
          v-model="time[0]"
          value-format="HH:mm:ss"
          placeholder="开始时间"
          :clearable="false"
          size="mini"
        ></el-time-picker>
      </el-form-item>
      <el-form-item label="结束日期:">
        <el-date-picker
          v-model="datetime[1]"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="结束日期"
          style="width: 130px"
          size="mini"
          :clearable="false"
        ></el-date-picker>
        <el-time-picker
          style="width:110px"
          v-model="time[1]"
          value-format="HH:mm:ss"
          placeholder="结束时间"
          :clearable="false"
          size="mini"
        ></el-time-picker>
      </el-form-item>
      <el-form-item class="searchmarigin">
        <el-button type="primary" @click="onSubmit" size="mini" icon="el-icon-search">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onExport" size="mini" icon="el-icon-document-copy">导出</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onExport('print')" size="mini" icon="el-icon-printer">打印</el-button>
      </el-form-item>
      <el-form-item>
        <el-popover width="500" placement="top" trigger="click">
          <el-row>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.departmentName.label"
              v-model="formThead.departmentName.checked"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.cardNumber.label"
              v-model="formThead.cardNumber.checked"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.userName.label"
              v-model="formThead.userName.checked"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.walletName.label"
              v-model="formThead.walletName.checked"
            ></el-checkbox>
          </el-row>
          <el-row>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.dataType.label"
              v-model="formThead.dataType.checked"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.expenditure.label"
              v-model="formThead.expenditure.checked"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.newBalance.label"
              v-model="formThead.newBalance.checked"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.dataMakeTime.label"
              v-model="formThead.dataMakeTime.checked"
            ></el-checkbox>
          </el-row>
          <el-row>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.userNumber.label"
              v-model="formThead.userNumber.checked"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.terminalCode.label"
              v-model="formThead.terminalCode.checked"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.isSuccess.label"
              v-model="formThead.isSuccess.checked"
            ></el-checkbox>
            <el-checkbox
              style="width: 10%"
              @change="getHeaderDate()"
              :label="formThead.serialNumber.label"
              v-model="formThead.serialNumber.checked"
            ></el-checkbox>
          </el-row>
          <el-button slot="reference" size="mini" type="primary" icon="el-icon-edit-outline">自定义</el-button>
        </el-popover>
      </el-form-item>
    </el-form>
    <div class="tablemain">
      <el-table
        v-loading="loading"
        :data="detailslist"
        ref="table"
        border
        highlight-current-row
        style="width: 100%"
        :header-cell-style="headFirst"
        :cell-style="
          detailsTotal ? (res) => headFirst_col(res, detailslist) : () => {}
        "
      >
        <!-- <el-table-column
               type="index"
              >
        </el-table-column>-->
        <el-table-column prop="userName" label="姓名" v-if="formThead.userName.checked"></el-table-column>
        <el-table-column
          prop="departmentName"
          label="部门"
          v-if="formThead.departmentName.checked"
          min-width="120px"
        ></el-table-column>

        <el-table-column
          prop="userNumber"
          label="人员编号"
          min-width="120px"
          v-if="formThead.userNumber.checked"
        ></el-table-column>
        <el-table-column
          prop="cardNumber"
          label="卡号"
          v-if="formThead.cardNumber.checked"
          min-width="100px"
        ></el-table-column>

        <el-table-column prop="walletName" label="消费钱包" v-if="formThead.walletName.checked"></el-table-column>
        <el-table-column
          prop="dataType"
          label="交易类型"
          v-if="formThead.dataType.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.dataType | filterchargingType }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="expenditure"
          label="操作金额(元)"
          v-if="formThead.expenditure.checked"
          min-width="110px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.expenditure | amountyuan }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="newBalance" label="卡内余额(元)" v-if="formThead.newBalance.checked">
          <template slot-scope="scope">
            <div>{{ scope.row.newBalance | amountyuan }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="consumePlace" label="使用场所" v-if="formThead.consumePlace.checked"></el-table-column>
        <el-table-column
          width="160"
          prop="dataMakeTime"
          label="操作时间"
          v-if="formThead.dataMakeTime.checked"
          min-width="120"
        ></el-table-column>
        <el-table-column prop="terminalCode" label="设备编号" v-if="formThead.terminalCode.checked"></el-table-column>
        <!-- <el-table-column
               prop="sumExpenditure"
               label="钱包类型"
            >
        </el-table-column>-->
        <el-table-column
          prop="isSuccess"
          label="交易状态"
          v-if="formThead.isSuccess.checked"
          min-width="100px"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.isSuccess | isSuccesstype }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="serialNumber" label="卡操作流水" v-if="formThead.serialNumber.checked"></el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChangepage"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="recordCount"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      filename: '刷卡明细报表',
      departmentoptions: [],
      departmentGuid: [],
      groupingoption: [],
      groupingGuid: [],
      userName: '',
      cardNumber: '',
      userNumber: '',
      datetime: [],
      time: [],
      dataType: [],
      elform: {},

      // 是否包含非确定交易
      includeNoSuccess: false,
      //
      detailslist: [],
      loading: false,
      pageNum: 1,
      pageSize: 20,
      currentPage: 1,
      recordCount: 0,
      searchInfo: {},
      formThead: {
        cardNumber: { label: '卡号', prop: 'cardNumber', checked: true },
        userName: { label: '姓名', prop: 'userName', checked: true },
        departmentName: {
          label: '部门',
          prop: 'departmentName',
          checked: true
        },
        userNumber: {
          label: '人员编号',
          prop: 'userNumber',
          checked: true
        },
        walletName: {
          label: '消费钱包',
          prop: 'walletName',
          checked: true
        },
        dataType: {
          label: '交易类型',
          prop: 'dataType',
          checked: true
        },
        expenditure: {
          label: '操作金额(元)',
          prop: 'expenditure',
          checked: true
        },
        newBalance: {
          label: '卡内余额(元)',
          prop: 'newBalance',
          checked: true
        },
        consumePlace: {
          label: '使用场所',
          prop: 'consumePlace',
          checked: true
        },
        dataMakeTime: {
          label: '操作时间',
          prop: 'dataMakeTime',
          checked: true
        },
        terminalCode: {
          label: '设备编号',
          prop: 'terminalCode',
          checked: true
        },
        isSuccess: { label: '交易状态', prop: 'isSuccess', checked: true },
        serialNumber: {
          label: '卡流水操作',
          prop: 'serialNumber',
          checked: true
        }
      },
      //导出数据
      detailslistExportlist: [],

      //汇总合计
      totalto: false,
      detailsTotal: null
    }
  },
  created() {
    this.datetime = [this.getNowTime('yy-mm-dd'), this.getNowTime('yy-mm-dd')]
    this.time = ['00:00:00', '23:59:59']
  },
  mounted() {
    this.departmentselectlist()
    this.unitgroup()
  },
  filters: {},
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid
      }
    }
  },
  methods: {
    // 重新渲染表格
    getHeaderDate() {
      this.$nextTick(() => {
        this.$refs['table'].doLayout()
      })
    },
    //合计查询
    searchtotal() {
      this.searchInfo.unitGuid = this.changeschoolid
      this.detailsTotal = null
      let _this = this
      _this.loading = true
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl('/terminal/hair/hair-drier-data-total'),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: _this.searchInfo,
              messageType: 0
            })
          })
          .then(({ data }) => {
            _this.loading = false
            if (data.messageCode == 200) {
              if (data.messageContent) {
                _this.detailsTotal = {
                  ...data.messageContent,
                  //   departmentName: "合计：",
                  newBalance: ''
                }
              }
              resolve(data.messageContent)
            } else {
              _this.$message.error(data.errorMessage)
              reject(data.errorMessage)
            }
          })
      })
    },
    //部门选择
    departmentselectlist() {
      this.departmentoptions = []
      this.$http({
        url: this.$http.adornUrl('/department/query-department-info'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            unitGuid: this.changeschoolid
          },
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].departmentGuid,
              label: Arr[i].departmentName
            }
            this.departmentoptions.push(itemobj)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    //单位分组查询
    unitgroup() {
      this.groupingoption = []
      this.$http({
        url: this.$http.adornUrl('/unit/unit-user-group-list'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: this.changeschoolid,
          messageType: 0
        })
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          let Arr = data.messageContent
          for (var i = 0; i < Arr.length; i++) {
            let itemobj = {
              value: Arr[i].groupGuid,
              label: Arr[i].groupName
            }
            this.groupingoption.push(itemobj)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    selectdepartment() {},
    // 查询
    async onSubmit() {
      this.pageNum = 1
      this.searchInfo = {}
      this.searchInfo.unitGuid = this.changeschoolid
      this.searchInfo.includeNoSuccess = this.includeNoSuccess
      if (this.departmentGuid != '') {
        this.searchInfo.departmentGuidList = this.departmentGuid
      }
      if (this.userName != '') {
        this.searchInfo.userName = this.userName
      }
      if (this.cardNumber != '') {
        this.searchInfo.cardNumber = this.cardNumber
      }
      if (this.userNumber != '') {
        this.searchInfo.userNumber = this.userNumber
      }
      //   if (this.groupingGuid != "") {
      //     this.searchInfo.groupGuidList = this.groupingGuid;
      //   }
      if (this.datetime != null && this.datetime != '') {
        this.searchInfo.startTime = this.datetime[0] + ' ' + this.time[0]
        this.searchInfo.endTime = this.datetime[1] + ' ' + this.time[1]
      }
      if (this.dataType !== null && this.dataType !== '') {
        this.searchInfo.chargingTypeList = this.dataType
      }
      await this.searchtotal()
      this.detailspage()
    },
    //刷卡明细分页查询
    detailspage() {
      this.loading = true
      this.searchInfo.unitGuid = this.changeschoolid
      this.$http({
        url: this.$http.adornUrl('/terminal/hair/hair-drier-data-page'),
        method: 'post',
        data: this.$http.adornData({
          messageContent: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            searchInfo: this.searchInfo
          },
          messageType: 0
        })
      }).then(({ data }) => {
        this.loading = false
        if (
          data.messageContent.data.length == 0 ||
          data.messageContent.data == null
        ) {
          this.$message({
            message: '查询成功当前暂无数据',
            type: 'success'
          })
        }
        if (data.messageCode == 200) {
          //   data = {
          //     errorMessage: "string",
          //     messageCode: 0,
          //     messageContent: {
          //       data: [
          //         {
          //           cardNumber: "123",
          //           dataGatherTime: "2020-11-21T01:42",
          //           dataGuid: "2132121ssadsad",
          //           dataMakeTime: "2020-11-21T01:42",
          //           dataType: 0,
          //           departmentGuid: "asdas121",
          //           departmentName: "一年级",
          //           expenditure: 110,
          //           isSuccess: 0,
          //           newBalance: 10,
          //           originBalance: 100,
          //           rechargeWay: 0,
          //           serialNumber: 0,
          //           terminalCode: "string",
          //           terminalName: "电吹风",
          //           unitGuid: "string",
          //           userGuid: "string",
          //           userName: "刘志强",
          //           userNumber: "123456",
          //           walletName: "消费钱包",
          //         },
          //       ],
          //       pageCount: 0,
          //       pageNum: 0,
          //       pageSize: 0,
          //       recordCount: 0,
          //     },
          //   };
          this.detailslist = data.messageContent.data
          this.recordCount = data.messageContent.recordCount
          this.currentPage = data.messageContent.pageNum
          if (this.detailslist != 0) {
            this.detailslist.push(this.detailsTotal)
          }
        } else {
          this.$message.error(data.errorMessage)
        }
      })
    },
    async onExport(type) {
      if (this.detailslist.length == 0) {
        this.$message({
          message: '请查询数据后,在进行此操作',
          type: 'warning'
        })
        return false
      }
      await this.outexecelinit()
      if (type == 'print') {
        this.printJS()
      } else {
        this.export2Excel()
      }
    },
    // 拿到表头数据
    getIsPrint() {
      const filterValArr = [
        'userName',
        'departmentName',
        'userNumber',
        'cardNumber',
        'walletName',
        'dataType',
        'expenditure',
        'newBalance',
        'consumePlace',
        'dataMakeTime',
        'terminalCode',
        'isSuccess',
        'serialNumber'
      ]
      let valArr = []
      let tHeader = []
      filterValArr.map(item => {
        if (this.formThead[item].checked) {
          valArr.push(this.formThead[item].prop)
          tHeader.push(this.formThead[item].label)
        }
      })
      return { filterValArr: valArr, tHeader }
    },
    // 打印
    printJS() {
      let someJSONdata = this.detailslistExportlist
      const title = '刷卡明细表'
      this.unitName = sessionStorage.getItem('unitName')
      const properties = []
      // 拿到数据,filterValArr为数据值，tHeader为数据标题，一一对应
      const { filterValArr, tHeader } = this.getIsPrint()
      filterValArr.map((item, index) => {
        if (filterValArr[index] == 'dataMakeTime') {
          properties.push({
            displayName: tHeader[index],
            field: filterValArr[index],
            columnSize: 180 / (Object.keys(this.formThead).length + 1) + '%'
          })
        } else {
          properties.push({
            displayName: tHeader[index],
            field: filterValArr[index],
            columnSize: 100 / (Object.keys(this.formThead).length + 1) + '%'
          })
        }
      })
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        /**
         * 获取表头的信息
         * @param {*} title 表名
         * @param {*} unitName 单位
         * @param {*} time 时间
         */
        header: this.printHeader(
          title,
          this.unitName,
          `${this.formatDate(
            new Date(this.searchInfo.startTime),
            'yyyy-MM-dd'
          )} 至 ${this.formatDate(
            new Date(this.searchInfo.endTime),
            'yyyy-MM-dd'
          )}`
        ),
        printable: someJSONdata,
        properties: properties,
        type: 'json',
        // 是否每页都显示头部
        // repeatTableHeader:false,
        headerRow: 1,
        /**
         * 获取页脚的信息
         * @param {*} loginName 制表人：
         * @param {*} time 时间
         */
        endPage: this.printFloor(
          sessionStorage.getItem('username'),
          this.getNowTime('yy-mm-dd hh:mm:ss')
        ),
        //  获取页脚的信息样式
        style: this.printFloorStyle()
      })
    },
    //刷卡明细导出数据
    outexecelinit() {
      let _this = this
      return new Promise(function(resolve, reject) {
        _this
          .$http({
            url: _this.$http.adornUrl('/terminal/hair/hair-drier-data-page'),
            method: 'post',
            data: _this.$http.adornData({
              messageContent: {
                pageNum: 1,
                pageSize: _this.recordCount,
                searchInfo: _this.searchInfo
              },
              messageType: 0
            })
          })
          .then(({ data }) => {
            if (data.messageCode == 200) {
              _this.detailslistExportlist = data.messageContent.data
              _this.detailslistExportlist.push({ ..._this.detailsTotal })
              for (var i = 0; i < _this.detailslistExportlist.length; i++) {
                _this.detailslistExportlist[
                  i
                ].dataType = _this.filterchargingType(
                  _this.detailslistExportlist[i].dataType
                )
                _this.detailslistExportlist[i].expenditure = _this.amountyua(
                  _this.detailslistExportlist[i].expenditure
                )
                _this.detailslistExportlist[i].newBalance = _this.amountyua(
                  _this.detailslistExportlist[i].newBalance
                )

                _this.detailslistExportlist[
                  i
                ].isSuccess = _this.$options.filters.isSuccesstype(
                  _this.detailslistExportlist[i].isSuccess
                )
              }
              resolve(_this.detailslistExportlist)
            } else {
              reject(data.errorMessage)
              _this.$message.error(data.errorMessage)
            }
          })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    export2Excel() {
      const nowtime = this.getimeto()
      require.ensure([], () => {
        const multiHeader = []
        const multiHeader2 = []
        const merges = []
        const { export_json_to_excel } = require('../../excel/Export2Excel')
        // tHeaderarr.push('部门名称')

        const { tHeader, filterValArr } = this.getIsPrint()
        const filterVal = filterValArr

        const list = this.detailslistExportlist
        const data = this.formatJson(filterVal, list)
        export_json_to_excel({
          multiHeader, //这里是第一行的表头
          multiHeader2, //这里是第二行的表头
          header: tHeader, //这里应该是算第三行的表头
          data,
          merges,
          filename: this.filename + nowtime
        })
      })
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.detailspage()
    },
    handleCurrentChangepage(val) {
      this.pageNum = val
      this.detailspage()
    }
  }
}
</script>

<style lang="scss" scoped>
.swipe_details {
  padding: 10px;
  //滚动条的宽度
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }

  //滚动条的滑块
  ::-webkit-scrollbar-thumb {
    background-color: #a1a3a9;
    border-radius: 3px;
  }

  .el-table__row .el-table__row--level-1 {
    background-color: #e5e9f2;
  }
  .el-form-item {
    margin-bottom: 5px;
  }
  .demo-form-inline,
  .demo-form-inline1 {
    /deep/.el-form-item__label {
      padding-right: 5px;
    }
    .el-form-item {
      margin-bottom: 5px;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 350px;
    }
  }
  .demo-form-inline1 {
    border-bottom: 1px solid #e5e9f2;
    .searchmarigin {
      margin-left: 20px;
    }
  }
  .page {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>